
import SDKNativeAdItem from "./SDKNativeAdItem";
import SDKAd from "./SDKAd";

/**
 * 原生广告
 */
export default class SDKNativeAd extends SDKAd {

    protected adItems: SDKNativeAdItem[] = []

    protected _index: number = 0
    protected _callback: (data: SDKNativeAdItem[]) => void;


    open(param?: { index: number, callback: (items: SDKNativeAdItem[]) => void }) {
        if (!this.has()) {
            param.callback([])
            return;
        }
        if (this.adItems.length > 0) {
            param.callback(this.adItems)
            this.adItems.length = 0;
        } else {
            this._index = param.index;
            this._callback = param.callback;
            console.log(" OppoNativeAd open", this._adUnitId)
            this.load()
        }
    }



    getItems() {
        return this.adItems;
    }

    private onError(err: any) {
        console.log(' BaseNativeAd onError err ', err)
        if (this._callback) {
            this._callback([])
        }
    }

    private onLoad(res: any) {
        console.log('onLoad ', res.adList)
        this.adItems.length = 0;
        if (res.adList) {
            for (let index = 0; index < res.adList.length; index++) {
                const element = res.adList[index];
                let adItem = new SDKNativeAdItem()
                adItem.init(element)
                this.reportAdShow(adItem.getID())
                this.adItems.push(adItem)
            }
            if (this._callback) {
                this._callback(this.adItems)
                this._callback = null;
            }
        }
    }

    protected load() {
        this.adItems.length = 0;
        this.destroy();
        if (!this.instance) {
            console.log('SGNativeAd load ', this._adUnitId)
            this.instance = this.sdk.createNativeAd({
                adUnitId: this._adUnitId[this._index],
                posId: this._adUnitId[this._index]
            });
            if (this.instance) {
                this.instance.onLoad(this.bind(this.onLoad))
                this.instance.onError(this.bind(this.onError))
            }
        }
        this.instance.load();

    }

    reportAdClick(adId: string) {
        if (!this.instance) {
            return
        }
        console.log('reportAdClick ', adId)
        this.instance.reportAdClick({
            adId: adId
        })
    }

    reportAdShow(adId: string) {
        if (!this.instance) {
            return
        }
        console.log('reportAdShow ', adId)
        this.instance.reportAdShow({
            adId: adId
        })
    }

    destroy() {
        if (this.instance) {
            this.instance.offLoad(this.unbind(this.onLoad))
            this.instance.offError(this.unbind(this.onError))
            this.instance.destroy();
            this._callback = null;
            this.instance = null;
        }

    }
}
